<%@ page language="java"
	import="com.google.appengine.api.users.*"
	import="jp.bluecab.bluecabsystem.locrecserv.classes.*"
	import="jp.bluecab.bluecabsystem.common.*"
	import="javax.jdo.*"
	import="java.util.*"
	contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	UserService userService = UserServiceFactory.getUserService(); // (1) ここから
	User user = userService.getCurrentUser();
	String email = user.getEmail(); // (1) ここまで

	PersistenceManager pm = PMF.get().getPersistenceManager(); //(2) ここから
	Query pmquery = pm.newQuery(LocRecUser.class);
	LocRecUser locRecUser = null;

	try {
		pmquery.setFilter("email == pEmail");
		pmquery.declareParameters("String pEmail");
		List<LocRecUser> results = (List<LocRecUser>) pmquery.execute(email); // (2)ここまで
		// 該当ユーザがいない場合は、ログインID登録画面へ移行する
		if (results.size() == 0) {
			response.sendRedirect("/location/signup.jsp"); // (3)
			return;
		}
		locRecUser = results.get(0);
	} finally {
		pm.close();
	}
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>BLUECabGPSSystem</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<link href="/css/locrecserv.css" rel="stylesheet" type="text/css" />
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="/css/jquery.clockpick.1.2.9.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.8.custom.min.js"></script>
<script type="text/javascript" src="/js/jquery.clockpick.1.2.9.min.js"></script>
<script type="text/javascript" src="/js/jquery.formnotifier.js"></script>
<script type="text/javascript" src="/js/dateformat.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&region=JP"></script>
<script type="text/javascript" src="/js/MarkerCluster.js"></script>
<script type="text/javascript" src="/js/suggest.js"></script>
<script type="text/javascript">

SuperMarker = function() {}
SuperMarker.prototype = new google.maps.Marker();

google.maps.Marker.prototype.addGpsRec = function(uid, op, c) {
	this.userid = uid;
	this.operationmode = op;

	var d = c.split(/[-:T+]/);
	d[1] -= 1;
	d.pop();
    var date = new Date(Date.UTC.apply(Date, d));
	//This gives us a Date object for the date specified, the rest is just formatting each component back into a string:
	//var ampm = date.getHours() > 12 ? "PM" : "AM";


	//var date = dateFormat.parse(c);
	this.createdAt = dispFormat.format(date);
}
google.maps.Marker.prototype.getUserid = function() {
	return this.userid;
}
google.maps.Marker.prototype.getOpmode = function() {
	return this.operationmode;
}
google.maps.Marker.prototype.getCreatedAt = function() {
	return this.createdAt;
}
var dateFormat = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
var dispFormat = new DateFormat("MM月dd日 HH:mm:ss 時点");

var complist = new Array();
var datalist = new Array();
var map;

$(document).ready(function() {

	//
	$(':input').formNotifier();
	//
	starAutotUpdate();

	//MAP
	var myOptions = {
		center: new google.maps.LatLng(33.150631, 129.740295), // 中央表示座標
		zoom: 13,
		mapTypeId: google.maps.MapTypeId.ROADMAP
		/**
			ROADMAP 、通常の表示で、2DのGoogle Mapsを表示
			SATELLITE 、鮮明な航空写真のタイルを表示
			HYBRID 、鮮明な航空写真のタイルに、有名な地物(道路や街の名前など）重ねて表示
			TERRAIN 、山や川などの地形的特徴を持つ地図を表示
		*/
	};
	map = new google.maps.Map($("#mainmap").get(0), myOptions);
	var markerClusterer = null;
	var infoWindow = new google.maps.InfoWindow;
	var onMarkerClick = function() {
		var _marker = this;
		var latLng = _marker.getPosition();
		infoWindow.setContent('<h3>'+ _marker.getUserid() + ' : </h3>' + _marker.getOpmode() + ', ' + _marker.getCreatedAt());// + latLng.lat() + ', ' + latLng.lng());
		infoWindow.open(map, _marker);
	};
	google.maps.event.addListener(map, 'click', function() {
		infoWindow.close();
	});

	$("#resbtn").click(function() {
		if (map.clearOverlays) map.clearOverlays();
		if (markerClusterer) markerClusterer.clearMarkers();
		$("#droplist").empty();
		complist.length = 0;
		datalist.length = 0;
        var query = {};
           query["tz"] ="Asia/Tokyo";

        if (!$('#dateAll').attr('checked')){
            query["datebegin"]=$("#dateBegin").val() + "-" + $("#timeBegin").val();
            query["dateend"]=$("#dateEnd").val() + "-" + $("#timeEnd").val();
        }
        $.getJSON("/api",query, function(json){
            var mapOptions = {
                //zoom: 13,
                //center: new google.maps.LatLng(json[0].latitude, json[0].longitude),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scaleControl: true
            };
            map.setOptions(mapOptions);

            //alert('ルートを表示するマップを設定');
            // ルートを表示するマップを設定
            var directionsRenderer = new google.maps.DirectionsRenderer();
            directionsRenderer.setMap(map);

            //alert(json.length);
            var markers = [];
            for (i =0; i < json.length; i=i+1){
            	// Create a new marker. Don't add it to the map!
            	var imgurl = "";
            	var op_str = "";
            	if (json[i].operationmode == 1) {
            		imgurl = "http://maps.google.co.jp/mapfiles/ms/icons/red-dot.png";
            		op_str = OPMODE_OP;
            	} else if (json[i].operationmode == 2) {
            		imgurl = "http://maps.google.co.jp/mapfiles/ms/icons/orange-dot.png";
            		op_str = OPMODE_REST;
            	} else if (json[i].operationmode == 3) {
            		continue;
            	}
        		var marker = new google.maps.Marker({
        			position: new google.maps.LatLng(json[i].latitude, json[i].longitude),
        			icon: imgurl,
        			title: json[i].userid + ' ： ' + op_str
        		});
        		marker.addGpsRec(json[i].userid, op_str, json[i].createdAt);
        		google.maps.event.addListener(marker, 'click', onMarkerClick);
        		markers.push(marker);

        		//リスト作成
        		var $jqObj = $("<div/>").addClass("J-N").css("-webkit-user-select", "none").attr("id", json[i].userid)
        								.attr("title", json[i].userid)
        								.attr("latitude", json[i].latitude)
        								.attr("longitude", json[i].longitude)
        								.hover(function(){
        									$(this).addClass("J-N-OV");
        								}, function(){
        									$(this).removeClass("J-N-OV");
        								})
        								.click(function(){
        									$("#btn_gps").removeClass("J-Zh-IO");
        									$("#drop").hide(200);
        									map.setCenter(new google.maps.LatLng($(this).attr("latitude"), $(this).attr("longitude")));
        									map.setZoom(17);
        								});

        		var $jqObj2 = $("<div/>").addClass("J-N-Jz").css("-webkit-user-select", "none").text(json[i].userid);
        		$jqObj.append($jqObj2);
        		$("#droplist").append($jqObj);

        		//コンプリート用リスト作成
        		complist.push(json[i].userid);
        		var pos = new google.maps.LatLng(json[i].latitude, json[i].longitude);
        		datalist[json[i].userid] = pos;

            }
            var mcOptions = {gridSize: 50, maxZoom: 13};
            markerClusterer = new MarkerClusterer(map, markers, mcOptions);

            //ボタンの情報更新
            $('#btn_gps').text(BTN_GPSSTR + '（' + markers.length + '）');
            //補完用リストソート
            complist.sort(Array.NUMERIC);

        });
	});

	//住所検索
	var geocoder = new google.maps.Geocoder();
	$('#sbtn').click(function() {
		var loc = $('#local').val();
		var sad = $('#address').val();
		geocoder.geocode({ 'address': loc + sad}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				//marker.setPosition(results[0].geometry.location);
				//var p = marker.position;
			} else {
				alert('住所から場所を特定できませんでした。');
			}
		});
		return false;
	});

	$('input.input_def').focus(function(){
		$(this).select();
	})
	.click(function(){
		$(this).select();
		return false;
	});

	//GPS車両一覧ドロップリスト
	$(function() {
		$('#btn_gps').click(function() {
			var o = $(this).offset();
			var h = $(this).outerHeight();
			$("#drop").css("left", o.left);
			$("#drop").css("top", o.top + h);
			$(this).toggleClass("J-Zh-IO");
			$("#drop").slideToggle(200);
		});
	});

	//車両検索
	new Suggest.Local(
			"searchno",    // 入力のエレメントID
			"suggest", // 補完候補を表示するエリアのID
			complist,      // 補完候補の検索対象となる配列
			{dispMax: 10, interval: 1000, prefix: true, highlight: true, hookAfterSelect: afterSugSel}); // オプション

	//更新
	$(".cb-enable").click(function(){
		var parent = $(this).parents('.switch');
		$('.cb-disable',parent).removeClass('selected');
		$(this).addClass('selected');
		$('.checkbox',parent).attr('checked', true);
		starAutotUpdate();
	});
	$(".cb-disable").click(function(){
		var parent = $(this).parents('.switch');
		$('.cb-enable',parent).removeClass('selected');
		$(this).addClass('selected');
		$('.checkbox',parent).attr('checked', false);
		stopAutoUpdate();
    });

});

var OPMODE_OP = "業務中";
var OPMODE_REST = "休憩中";
var BTN_GPSSTR = "GPS稼働車一覧";
//onEnter
function enter(){
	if( window.event.keyCode == 13 ){
		$('#sbtn').click();
	}
}
//onEnter
function enter_no(){
	if( window.event.keyCode == 13 ){
		afterSugSel($("#searchno").value);
	}
}
//検索した車両をセンターに
function afterSugSel(txt) {
	if (!datalist[txt]) return;

	var p = datalist[txt];
	map.setCenter(p);
	map.setZoom(17);
}

var tid;
function starAutotUpdate(){
	tid = setInterval( "excecuteUpdate()", 30000 );
}
function excecuteUpdate(){
	$("#resbtn").click();
}
function stopAutoUpdate(){
	clearInterval(tid);
}

</script>
<body>
	<div id="header">
		<div id="logo">
			<h1>
				<a href="#" onclick="$('#resbtn').click()">BLUE Cab GPS System</a>
			</h1>
		</div>
		<div id="menu">
			<ul>
				<div align="right">
					ログインユーザー： <%= locRecUser.getLoginId() %>
					<a href="/location/history.jsp">行動履歴</a>
					<a href="<%=userService.createLogoutURL("/")%>">ログアウト</a>
				</div>
			</ul>
		</div>
	</div>

	<div id="wrapper">
		<div id="page">
			<div id="content" style="width: 100%;">
				<div class="post">
					<div class="entry">
						<table style="height: 100%; width: 100%;">
							<tr style="height: 20px;"><td>
								<input type="text" class="input_def" id="local" size="15" value="長崎県佐世保市 " title="地区指定" />
								<input type="text" class="input_def" id="address" size="50" value="" onkeypress="enter()" title="地域検索" />
								<input type="button" id="sbtn" class="sb" value="検索" />
								<div id="btn_gps" class="J-Zh-I" act="20" role="button" tabindex="0" style="-webkit-user-select: none; ">GPS稼働車一覧（0）</div>

								<input type="text" class="input_def" id="searchno" maxlength="200" size="8" onkeypress="enter_no()" ignoreesc="true" style="ime-mode: disabled;" autocomplete="off"
										onkeypress='javascript:if(event.keyCode<"0".charCodeAt(0) || "9".charCodeAt(0)<event.keyCode) return false;' title="車両検索" />

								<!-- 補完候補を表示するエリア -->
        						<div id="suggest" style="display:none;"></div>
							</td>
							<td align="right">
								<div id="drop" class="J-M" style="-webkit-user-select: none; left: 5px; top: 8px; display: none;" role="menu" aria-haspopup="true" aria-activedescendant="">
									<div class="SK AX" style="-webkit-user-select: none; ">
<!-- 										<div class="J-M-JJ" style="-webkit-user-select: none; "> -->
<!-- 											<div style="-webkit-user-select: none; visibility: visible; "></div> -->
<!-- 											<input type="text" maxlength="225" ignoreesc="true" style="" tabindex="0"> -->
<!-- 											<div class="A0" style="-webkit-user-select: none; "></div> -->
<!-- 										</div> -->
										<div id="droplist" class="J-M-Jz" style="-webkit-user-select: none; min-width: 104px; ">
											<!-- ここにリスト表示 -->
										</div>
										<div class="J-Kh" style="-webkit-user-select: none; " role="separator" id=":vq"></div>
										<div class="J-JK-Jz" style="-webkit-user-select: none; "></div></div>
								</div>


								<p class="field switch">
									<input type="radio" id="radio1" name="field" value="0"  checked />
									<input type="radio" id="radio2" name="field" value="1" />
									<label for="radio1" class="cb-enable selected"><span>自動更新</span></label>
									<label for="radio2" class="cb-disable"><span>手動更新</span></label>
								</p>
								<input type="submit" id="resbtn" class="sb" value="更新" />
							</td></tr>
							<tr><td colspan="2">
								<div id="mainmap" style="width: 100%; height: 100%"></div>
							</td></tr>
						</table>

					</div>
				</div>
			</div>
<!--
			<div id="sidebar">
				<ul>
					<li>
						<p>ようこそ <%= locRecUser.getLoginId() %> さん</p>

						<h2>読込条件</h2>
						<ul><% if (userService.isUserAdmin()){ %><li><a href='/admin/index.jsp'>管理画面</a></li><% } %>
                    <li><input id="dateAll" type="checkbox" value="1"/>最新情報</li>
                    <h3>開始</h3>
                    <li>
                        <input id="dateBegin" type="text" value="2010/1/1" />
                        <input id="timeBegin" type="text" value="9:00">
                    </li>
                    <h3>終了</h3>
                    <li>
                        <input id="dateEnd" type="text"  value="2012/1/1" />
                        <input id="timeEnd" type="text" value="10:00">
                    </li>
                    <li><input type="submit" id="resbtn" value="更新" /></li>
                    </ul>
                    </li>
				</ul>
			</div> -->
		</div>
	</div>
			<div id="footer" style="clear: both;">Copyright &copy  BLUE Cab Group. SaseboTaxi Inc. All Rights Reserved.</div>

</body>
</html>
